package cn.bo.cloud.demo2.web;


import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.Rule;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * 代码方式配置sentinel流控
 */
@RestController
@RequestMapping("/server")
public class ServerController {

    @Value("${server.port}")
    String port;

    private static final String RESOURCE_NAME = "uri2";

    @RequestMapping("/uri1")
    public String test01(){

        return "server-u1-" + port;

    }

    @RequestMapping(value = "/uri2", produces = "application/json;charset=UTF-8")
    public String test02(){

        Entry entry = null;
        try {
            // sentinel 针对资源进行流控
            entry = SphU.entry(RESOURCE_NAME);
            // 被保护的业务逻辑
            String str = "hello world";
            return "sentinel-core-server-uri2";
        } catch (BlockException e) {
            return "被流控了";
        }catch (Exception e){
            Tracer.traceEntry(e, entry);
        }finally {
            if(entry != null){
                entry.exit();
            }
        }


//        return "server-u2";
        return null;
    }

    @PostConstruct
    private static void initFlowRules(){
        // 流控规则
        List<FlowRule> rules = new ArrayList<>();

        // 流控
        FlowRule rule = new FlowRule();
        // 设置受保护的资源
        rule.setResource(RESOURCE_NAME);
        // 设置流控规则QPS
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 设置受保护的资源阈值
        // set limit QPS to 20.
        rule.setCount(1);
        rules.add(rule);

        FlowRuleManager.loadRules(rules);

        // 通过@SentinelResource来定义资源
    }

}
